<template>
    <div class="printMgt-index yuan-container">
        <a-card title="打印管理">
            <div class="filter-panel">
                <a-input-search class="filter-list" allowClear v-model="keywords" placeholder="请输入关键词" @search="resetList" />
                <div class="filter-list" style="float: right;">
                    <a-button type="primary" @click="download" :loading="downloadLoading"
                        v-if="$utilCheckPermission(['printManagementExport'])">导出</a-button>
                </div>
            </div>
            <div class="table">
                <a-table bordered :rowKey="item=>item.id" :data-source="pageList" :columns="columns" :pagination="pagination"
                    :loading="loading">
                </a-table>
            </div>
        </a-card>
        <a-modal width="600px" title="增加打印量" :visible="addPrintVisible" @ok="addPrintOk" @cancel="addPrintCancel" okText="确定"
            cancelText="取消">
            <a-spin tip="Loading..." :spinning="addPrintLoading">
                <a-form-model layout="inline" class="yuan-form" :label-col="{ style: { width: '100px' } }"
                    :wrapper-col="{ style: { width: 'calc(100% - 120px)' } }">
                    <div class="form-panel">
                        <a-form-model-item label="增加打印量" prop="addPrintInfo">
                            <a-input type="number" v-model="addPrintInfo" placeholder="请输入打印量" />
                        </a-form-model-item>
                    </div>
                </a-form-model>
            </a-spin>
        </a-modal>
        <DetailVue :visible="detailVisible" @closeModal="() => detailVisible = false" :infoId="detailId" @resetList="getList" />
        <SendVue :visible="sendVisible" @closeModal="() => sendVisible = false" :infoId="sendId" @resetList="getList" />
    </div>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import { h } from "vue";
import nextApi, { PrintInfoListRes } from "@/api/nextApi";
import DetailVue from "./components/detail.vue";
import { downLoadFile, format } from "@/utils";
import SendVue from "./components/send.vue";
@Component({
    name: "printMgtMgtIndex",
    components: { DetailVue, SendVue },
})
export default class extends Vue {
    pagination = {
        pageSize: 10,
        current: 1,
        total: 0,
        showTotal: (total: number) => `共${total}条`,
        onChange: this.pageChange,
    };
    columns = [
        {
            align: "center",
            dataIndex: "productBigKind",
            key: "productBigKind",
            title: "产品大类",
        },
        {
            align: "center",
            dataIndex: "productType",
            key: "productType",
            title: "产品类型",
        },
        {
            align: "center",
            dataIndex: "varietyName",
            key: "varietyName",
            title: "名称",
        },
        {
            align: "center",
            dataIndex: "discretion",
            key: "discretion",
            title: "装量",
        },
        {
            align: "center",
            dataIndex: "productBatch",
            key: "productBatch",
            title: "包装批号",
        },
        {
            align: "center",
            dataIndex: "productionTime",
            key: "productionTime",
            title: "生产日期",
        },
        {
            align: "center",
            dataIndex: "expirationDate",
            key: "expirationDate",
            title: "保质期(月)",
        },
        {
            align: "center",
            dataIndex: "medicineClass",
            key: "medicineClass",
            title: "中药等级",
            customRender: (text: string, record: any, index: number) => `${record.medicineClass?record.medicineClass:'-'}-${record.medicineValue?record.medicineValue:'-'}`,
        },
        {
            align: "center",
            dataIndex: "printState",
            key: "printState",
            title: "状态",
            customRender: (text: string, record: PrintInfoListRes, index: number) => {
                if (record.printState === 0) {
                    return `未发送`;
                } else {
                    return `发送(${record.printNum})`;
                }
            },
        },

        {
            align: "center",
            dataIndex: "action",
            key: "action",
            title: "操作",
            width: 360,
            customRender: (text: string, record: PrintInfoListRes, index: number) => {
                const detailH = h(
                    "a-button",
                    {
                        style: { marginRight: "5px" },
                        props: { icon: "eye", type: "primary", size: "small" },
                        on: { click: () => this.showDetail(record) },
                    },
                    "查看"
                );

                const sendH = h(
                    "a-button",
                    {
                        style: { marginRight: "5px" },
                        props: { icon: "tool", type: "primary", size: "small" },
                        on: { click: () => this.send(record) },
                    },
                    "发送"
                );
                const addPrintH = h(
                    "a-button",
                    {
                        style: { marginRight: "5px" },
                        props: { icon: "info-circle", type: "warning", size: "small" },
                        on: { click: () => this.addPrint(record) },
                    },
                    "增加打印量"
                );
                const downloadH = h(
                    "a-button",
                    {
                        style: { marginRight: "5px" },
                        props: { icon: "info-circle", type: "warning", size: "small" },
                        on: { click: () => this.rowDownload(record) },
                    },
                    "下载"
                );
                const btnArr: any = [];

                if (this.$utilCheckPermission(["printManagementDetails"])) btnArr.push(detailH);
                if (this.$utilCheckPermission(["printManagementSend"])) btnArr.push(sendH);
                if (this.$utilCheckPermission(["printManagementAddPrintNum"])) btnArr.push(addPrintH);
                if (this.$utilCheckPermission(["printManagementDownload"])) btnArr.push(downloadH);

                return h("div", btnArr);
            },
        },
    ];
    loading = false;
    pageList: PrintInfoListRes[] = [];
    keywords = "";
    async getList() {
        this.pageList = [];
        try {
            this.loading = true;
            const res = await nextApi.getPrintInfoList({
                pageSize: this.pagination.pageSize,
                pageNum: this.pagination.current,
                varietyName: this.keywords,
            });
            this.pagination.total = res.data?.total || 0;
            this.pageList = res.data?.rows || [];
        } finally {
            this.loading = false;
        }
    }
    resetList() {
        this.pagination.current = 1;
        this.getList();
    }
    pageChange(page: number, pageSize: number) {
        this.pagination.pageSize = pageSize;
        this.pagination.current = page;
        this.getList();
    }
    async mounted() {
        this.getList();
    }
    detailId = "";
    detailVisible = false;
    showDetail(item: PrintInfoListRes) {
        this.detailId = item.id;
        this.detailVisible = true;
    }

    addPrintVisible = false;
    addPrintId = "";
    addPrintInfo = "";
    addPrintLoading = false;
    addPrint(item: PrintInfoListRes) {
        this.addPrintId = item.id;
        this.addPrintVisible = true;
        this.addPrintInfo = "";
    }
    async addPrintOk() {
        this.addPrintLoading = true;
        try {
            const res = await nextApi.addPrintNum({
                id: this.addPrintId,
                printNum: this.addPrintInfo,
            });
            this.$message.success(res.msg);
            this.addPrintVisible = false;
        } finally {
            this.addPrintLoading = false;
        }
    }
    addPrintCancel() {
        this.addPrintInfo = "";
        this.addPrintVisible = false;
    }
    downloadLoading = false;
    download() {
        this.downloadLoading = true;
        nextApi.downloadPrintList(this.keywords, (res: any) => {
            const blob = new Blob([res.data], {
                type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                // type: "application/vnd.ms-excel",
            });
            downLoadFile(blob, "打印数据列表");
            this.downloadLoading = false;
        });
    }
    rowDownload(item: any) {
        this.loading = true;
        const params = {
            id: item.id,
            // 品名: item.varietyName,
            // 药材产地: item.placeOfOrigin,
            // 产品批号: item.productBatch,
            // 生产日期: format(item.productionTime, "yyyy.MM.dd"),
            // 保质期至: this.getExpirationDateTime(item),
            // 规格: item.specification,
            // 装量: "每袋装" + item.discretion,
            // 贮藏: item.stockpileCondition,
            // 执行标准: item.executiveStandard,
        };
        // let content = JSON.stringify(params);
        nextApi.downloadPrintOne(params, (res: any) => {
            const blob = new Blob([res.data], {
                //type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                type: "text/plain",
            });
            downLoadFile(blob, "打印二维码");
            this.loading = false;
        });
    }

    sendVisible = false;
    sendId = "";
    send(item: PrintInfoListRes) {
        this.sendVisible = true;
        this.sendId = item.id;
    }
    getExpirationDateTime(detailData) {
        if (!detailData.productionTime) return "";
        const productionTime = detailData.productionTime;
        let productionArr: string[] = [];
        if (productionTime.indexOf("/") >= 0) {
            productionArr = productionTime.split("/");
        } else if (productionTime.indexOf("-") >= 0) {
            productionArr = productionTime.split("-");
        }
        const month = Number(productionArr[1]) +  Number(detailData.expirationDate);
        const addYear = Math.floor(month / 12);

        const addMonth = month % 12 === 0 ? 12 : month % 12;
        return `${Number(productionArr[0]) + addYear}年${addMonth}月`;
    }
}
</script>
<style lang="scss">
.printMgt-index {
    padding: 20px;
}
</style>
